import axios from 'axios/dist/browser/axios.cjs';
import {
  getToken,
  setToken,
  getRefreshToken,
  setRefreshToken,
  clearStorage
} from "../utils/auth";
import { Message } from "element-ui";

let requestQueue = [];
let isRefreshing = false;

const instance = axios.create({
  withCredentials: true,
  crossDomain: true
});

// 请求拦截
instance.interceptors.request.use(
  config => {
    let token = getToken();
    //设置请求头
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    let refreshToken = getRefreshToken();
    //设置请求头
    if (refreshToken) {
      config.headers["RefreshToken"] = refreshToken;
    }
    console.log("发送的请求信息", config);
    //返回配置信息
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  response => {
    console.log(`[DEBUG:请求成功「${new Date()}」]`, response);
    if (response.status >= 200 && response.status < 300) {
      if (response.data.code === 0) {
        //用于Token存储
        if (response.data.token) {
          setToken(response.data.token);
        }
        //用于RefreshToken存储
        if (response.data.refreshToken) {
          setRefreshToken(response.data.refreshToken);
        }
        return Promise.resolve(response.data.data);
      } else {
        //处理40000-50000自动报错
        if (response.data.code >= 40000 && response.data.code < 50000) {
          console.log("40000");
        }
        return Promise.reject(response.data);
      }
    }
    return Promise.reject(response);
  },
  async error => {
    console.error(`[DEBUG:请求报错「${new Date()}」]`, error);
    if (error.response) {
      let { status, data } = error.response;
      if (status > 300) {
        const originalRequest = error.config;
        // 初始化 _retry 属性为 false
        originalRequest._retry = originalRequest._retry || false;
        //判断如果状态401,则需要进入
        if (status === 401 && !originalRequest._retry) {
          originalRequest._retry = true;
          const refreshToken = getRefreshToken();
          if (refreshToken) {
            if (!isRefreshing) {
              isRefreshing = true;
              try {
                let response = await axios.post("/api/login/refresh", {
                  refreshToken
                });
                if (response.data.data.token) {
                  setToken(response.data.data.token);
                }
                if (response.data.data.refreshToken) {
                  setRefreshToken(response.data.data.refreshToken);
                }
                requestQueue.forEach(queuedRequest => {
                  queuedRequest.headers.Authorization = `Bearer ${response.data.data["token"]}`;
                  //console.log("列队获取", originalRequest);
                  axios(queuedRequest);
                });
                requestQueue = [];
                isRefreshing = false;
                originalRequest.headers.Authorization = `Bearer ${response.data.data["token"]}`;
                // console.log("原始调取", originalRequest);

                response = await axios(originalRequest);
                if (response.data.code === 0) {
                  return Promise.resolve(response.data.data);
                } else {
                  return Promise.resolve(response);
                }
              } catch (refreshError) {
                clearStorage();
                isRefreshing = false;
                console.error("Refresh token failed:", refreshError);
                return Promise.reject(refreshError);
              }
            } else {
              return new Promise((resolve, reject) => {
                const intervalId = setInterval(() => {
                  if (!isRefreshing) {
                    clearInterval(intervalId);
                    originalRequest.headers.Authorization = `Bearer ${getToken()}`;
                    // console.log("等待调取", originalRequest);
                    axios(originalRequest)
                      .then(resolve)
                      .catch(reject);
                  }
                }, 100);
              });
            }
          } else {
            return Promise.reject(error);
          }
        }
        if (data && data.code) {
          Message({
            message: `[${data.code}]-${data.msg}`,
            type: "warning"
          });
          //此处需要自动报错
          return Promise.reject(data);
        }
      }

      return Promise.reject(error.response);
    }
    return Promise.reject(error);
  }
);

export default instance;
